package com.blog.cmrpersonalblog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.cmrpersonalblog.common.PageResult;
import com.blog.cmrpersonalblog.dto.article.request.ArticleCommentListRequest;
import com.blog.cmrpersonalblog.dto.article.response.ArticleCommentResponse;
import com.blog.cmrpersonalblog.dto.comment.request.CommentCreateRequest;
import com.blog.cmrpersonalblog.dto.comment.request.CommentLikeRequest;
import com.blog.cmrpersonalblog.dto.comment.request.CommentTreeRequest;
import com.blog.cmrpersonalblog.dto.comment.responst.CommentLikeResponse;
import com.blog.cmrpersonalblog.dto.comment.responst.CommentStatsResponse;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordCheckResult;
import com.blog.cmrpersonalblog.entity.Comment;
import com.blog.cmrpersonalblog.entity.UserLike;

import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import com.blog.cmrpersonalblog.enums.ActivityType;
import com.blog.cmrpersonalblog.entity.CommentMention;
import com.blog.cmrpersonalblog.mapper.ArticleMapper;
import com.blog.cmrpersonalblog.mapper.CommentMapper;
import com.blog.cmrpersonalblog.mapper.CommentMentionMapper;
import com.blog.cmrpersonalblog.mapper.UserLikeMapper;
import com.blog.cmrpersonalblog.mapper.SysUserMapper;
import com.blog.cmrpersonalblog.service.CommentManagementService;
import com.blog.cmrpersonalblog.service.NotificationService;
import com.blog.cmrpersonalblog.service.SensitiveWordService;
import com.blog.cmrpersonalblog.service.UserActivityService;
import com.blog.cmrpersonalblog.service.UserCommentService;
import com.blog.cmrpersonalblog.service.CommentImageService;
import com.blog.cmrpersonalblog.utils.MentionUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;

import java.util.List;

/**
 * 用户端评论服务实现类
 */
@Slf4j
@Service
public class UserCommentServiceImpl implements UserCommentService {

   @Resource
    private CommentMapper commentMapper;

   @Resource
    private ArticleMapper articleMapper;

   @Resource
    private UserLikeMapper userLikeMapper;

   @Resource
    private CommentManagementService commentManagementService;

   @Resource
    private SensitiveWordService sensitiveWordService;

   @Resource
    private UserActivityService userActivityService;

   @Resource
    private CommentImageService commentImageService;

   @Resource
    private NotificationService notificationService;

   @Resource
    private CommentMentionMapper commentMentionMapper;

   @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    public List<ArticleCommentResponse> getArticleComments(ArticleCommentListRequest request) {
        log.info("获取文章评论列表: articleId={}, topLevelOnly={}", request.getArticleId(), request.getTopLevelOnly());
        
        // 应用排序类型
        request.applySortType();
        
        // 获取当前用户ID（如果已登录）
        Long currentUserId = null;
        try {
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }
        } catch (Exception e) {
            log.debug("用户未登录，以游客身份获取文章列表");
            // 用户未登录，忽略异常
        }
        
        // 查询评论列表
        List<ArticleCommentResponse> comments = commentMapper.selectArticleComments(request, currentUserId);
        
        log.info("查询到评论数量: {}", comments.size());
        return comments;
    }


    @Override
    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    public PageResult<ArticleCommentResponse> getCommentTree(CommentTreeRequest request) {
        log.info("获取评论树形结构: articleId={}, maxLevel={}, childrenLimit={}, twoLevelMode={}", 
                request.getArticleId(), request.getMaxLevel(), request.getChildrenLimit(), request.isTwoLevelMode());
        
        // 应用排序设置
        request.applySortType();
        
        // 获取当前用户ID（如果已登录）
        Long currentUserId = null;
        try {
            if (StpUtil.isLogin()) {
                currentUserId = StpUtil.getLoginIdAsLong();
            }
        } catch (Exception e) {
            log.debug("用户未登录，以游客身份获取评论树");
        }
        
        // 分页查询顶级评论
        Page<ArticleCommentResponse> page = new Page<>(request.getCurrent(), request.getSize());
        IPage<ArticleCommentResponse> topLevelComments = commentMapper.selectTopLevelCommentsPage(
                page, request.getArticleId(), currentUserId, request.getSortSql());
        
        if (topLevelComments.getRecords().isEmpty()) {
            return PageResult.of(new ArrayList<>(), topLevelComments.getTotal(), 
                                topLevelComments.getCurrent(), topLevelComments.getSize());
        }
        
        // 如果只要根评论，不加载回复
        if (request.getRootOnly()) {
            log.info("只加载根评论，跳过回复查询");
            return PageResult.of(topLevelComments.getRecords(), topLevelComments.getTotal(), 
                                topLevelComments.getCurrent(), topLevelComments.getSize());
        }
        
        // 获取所有顶级评论的ID
        List<Long> topLevelIds = topLevelComments.getRecords().stream()
                .map(ArticleCommentResponse::getId)
                .collect(Collectors.toList());
        
        // 固定使用两层级扁平化模式
        List<ArticleCommentResponse> commentTree = buildTwoLevelCommentTree(
                topLevelComments.getRecords(), topLevelIds, currentUserId, request);
        
        log.info("构建评论树完成: 顶级评论={}, 模式=两层级扁平化", topLevelIds.size());
        
        return PageResult.of(commentTree, topLevelComments.getTotal(), 
                            topLevelComments.getCurrent(), topLevelComments.getSize());
    }

    /**
     * 构建评论树形结构
     */
    private List<ArticleCommentResponse> buildCommentTree(List<ArticleCommentResponse> topLevelComments,
                                                          List<ArticleCommentResponse> allChildren,
                                                          Integer childrenLimit) {
        
        // 按父ID分组子评论
        Map<Long, List<ArticleCommentResponse>> childrenMap = allChildren.stream()
                .collect(Collectors.groupingBy(ArticleCommentResponse::getParentId));
        
        // 为每个顶级评论设置子评论
        for (ArticleCommentResponse topComment : topLevelComments) {
            setChildrenRecursively(topComment, childrenMap, childrenLimit, 1, 3);
        }
        
        return topLevelComments;
    }

    /**
     * 递归设置子评论
     */
    private void setChildrenRecursively(ArticleCommentResponse parent, 
                                       Map<Long, List<ArticleCommentResponse>> childrenMap,
                                       Integer childrenLimit, 
                                       Integer currentLevel, 
                                       Integer maxLevel) {
        
        if (currentLevel >= maxLevel) {
            return;
        }
        
        List<ArticleCommentResponse> children = childrenMap.get(parent.getId());
        if (children == null || children.isEmpty()) {
            parent.setChildren(new ArrayList<>());
            parent.setHasMoreChildren(false);
            parent.setChildrenTotal(0);
            return;
        }
        
        // 限制子评论数量
        boolean hasMore = children.size() > childrenLimit;
        List<ArticleCommentResponse> limitedChildren = children.stream()
                .limit(childrenLimit)
                .collect(Collectors.toList());
        
        parent.setChildren(limitedChildren);
        parent.setHasMoreChildren(hasMore);
        parent.setChildrenTotal(children.size());
        
        // 递归处理子评论的子评论
        for (ArticleCommentResponse child : limitedChildren) {
            setChildrenRecursively(child, childrenMap, childrenLimit, currentLevel + 1, maxLevel);
        }
    }

    /**
     * 构建两层级评论树（类似微博、知乎的扁平化回复结构）
     */
    private List<ArticleCommentResponse> buildTwoLevelCommentTree(
            List<ArticleCommentResponse> rootComments, 
            List<Long> rootIds,
            Long currentUserId,
            CommentTreeRequest request) {
        
        if (rootComments.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 查询所有根评论的回复（扁平化）
        List<ArticleCommentResponse> allReplies = commentMapper.selectFlatRepliesByParentIds(
                rootIds, currentUserId, request.getChildrenLimit(), request.getReplySortSql());
        
        log.info("两层级模式查询回复: 根评论数={}, 回复总数={}", rootIds.size(), allReplies.size());
        
        // 按父评论ID分组回复
        Map<Long, List<ArticleCommentResponse>> repliesMap = allReplies.stream()
                .collect(Collectors.groupingBy(ArticleCommentResponse::getParentId));
        
        // 为每个根评论设置其回复
        for (ArticleCommentResponse rootComment : rootComments) {
            List<ArticleCommentResponse> replies = repliesMap.get(rootComment.getId());
            
            if (replies != null && !replies.isEmpty()) {
                // 应用回复数量限制
                boolean hasMoreReplies = replies.size() > request.getChildrenLimit();
                List<ArticleCommentResponse> limitedReplies = replies.stream()
                        .limit(request.getChildrenLimit())
                        .collect(Collectors.toList());
                
                // 为回复设置显示格式（扁平化，无嵌套children）
                limitedReplies.forEach(reply -> {
                    reply.setChildren(new ArrayList<>());
                    reply.setHasMoreChildren(false);
                    reply.setChildrenTotal(0);
                });
                
                rootComment.setChildren(limitedReplies);
                rootComment.setHasMoreChildren(hasMoreReplies);
                rootComment.setChildrenTotal(replies.size());
            } else {
                rootComment.setChildren(new ArrayList<>());
                rootComment.setHasMoreChildren(false);
                rootComment.setChildrenTotal(0);
            }
        }
        
        return rootComments;
    }

    @Override
    @Transactional
    public ArticleCommentResponse createComment(CommentCreateRequest request, Long userId, String clientIp, String userAgent) {
        log.info("创建评论: articleId={}, userId={}, isReply={}", request.getArticleId(), userId, request.isReplyComment());
        
        // 检查文章是否可评论
        if (!canUserComment(request.getArticleId(), userId)) {
            throw new RuntimeException("文章不存在或不允许评论");
        }
        
        // 创建评论对象
        Comment comment = new Comment();
        comment.setArticleId(request.getArticleId());
        comment.setUserId(userId);
        comment.setContent(request.getContent());
        comment.setParentId(request.getEffectiveParentId());
        comment.setReplyToUserId(request.getReplyToUserId());
        comment.setIpAddress(clientIp);
        comment.setUserAgent(userAgent);
        comment.setStatus(1); // 正常状态
        comment.setLikeCount(0);
        comment.setReplyCount(0);
        
        // 处理层级和路径（强制两层级结构）
        if (request.isTopLevelComment()) {
            // 顶级评论
            comment.setLevel(1);
            comment.setRootId(null); // 将在保存后设置为自己的ID
        } else {
            // 回复评论（强制为二级，不允许多层嵌套）
            Comment parentComment = commentMapper.selectById(request.getParentId());
            if (parentComment == null) {
                throw new RuntimeException("父评论不存在");
            }
            
            // 强制两层级：如果回复的是子评论，则将其转为对根评论的回复
            Long rootId = parentComment.getRootId() != null ? parentComment.getRootId() : parentComment.getId();
            comment.setLevel(2); // 固定为第2层
            comment.setRootId(rootId);
            
            // 如果原本是对子评论的回复，调整为对根评论的回复，但保留replyToUserId
            if (parentComment.getLevel() > 1) {
                log.info("将多层嵌套回复转换为对根评论的回复: 原parentId={}, 新parentId={}", 
                        request.getParentId(), rootId);
                comment.setParentId(rootId); // 改为对根评论的直接回复
            }
        }
        
        // 敏感词检测和处理
        SensitiveWordCheckResult sensitiveResult = sensitiveWordService.checkSensitiveWords(request.getContent());
        if (sensitiveResult.isHasSensitiveWords()) {
            comment.setOriginalContent(request.getContent());
            comment.setContent(sensitiveResult.getFilteredContent()); // 使用过滤后的内容
            comment.setIsSensitive(1);
            // 将敏感词列表转换为JSON字符串
            if (sensitiveResult.getSensitiveWords() != null && !sensitiveResult.getSensitiveWords().isEmpty()) {
                try {
                    StringBuilder wordsJson = new StringBuilder("[");
                    for (int i = 0; i < sensitiveResult.getSensitiveWords().size(); i++) {
                        if (i > 0) wordsJson.append(",");
                        wordsJson.append("\"").append(sensitiveResult.getSensitiveWords().get(i).getWord()).append("\"");
                    }
                    wordsJson.append("]");
                    comment.setSensitiveWords(wordsJson.toString());
                } catch (Exception e) {
                    comment.setSensitiveWords("[]");
                }
            } else {
                comment.setSensitiveWords("[]");
            }
            comment.setSensitiveType(sensitiveResult.getPrimaryType());
            comment.setSensitiveScore(sensitiveResult.getSensitiveScore());
        } else {
            comment.setIsSensitive(0);
            comment.setSensitiveScore(0);
        }
        
        // 保存评论
        boolean saved = commentManagementService.createComment(comment);
        if (!saved) {
            throw new RuntimeException("评论创建失败");
        }
        
        // 如果是顶级评论，设置rootId为自己的ID
        if (request.isTopLevelComment()) {
            comment.setRootId(comment.getId());
            commentMapper.updateById(comment);
        }
        
        // 构建评论路径
        String path = commentManagementService.buildCommentPath(comment);
        comment.setPath(path);
        commentMapper.updateById(comment);
        
        // 更新父评论的回复数
        if (!request.isTopLevelComment()) {
            commentManagementService.updateCommentStats(request.getParentId(), "reply_count", 1);
        }
        
        // 处理评论图片（如果有）
        try {
            if (request.getTempImageIds() != null && !request.getTempImageIds().isEmpty()) {
                // 通过临时图片ID关联图片
                boolean imageAttached = commentImageService.attachImagesToComment(comment.getId(), request.getTempImageIds(), userId);
                if (!imageAttached) {
                    log.warn("评论图片关联失败: commentId={}, tempImageIds={}", comment.getId(), request.getTempImageIds());
                }
            } else if (request.getUploadTokens() != null && !request.getUploadTokens().isEmpty()) {
                // 通过上传令牌关联图片
                boolean imageAttached = commentImageService.attachImagesByTokens(comment.getId(), request.getUploadTokens(), userId);
                if (!imageAttached) {
                    log.warn("评论图片关联失败: commentId={}, uploadTokens={}", comment.getId(), request.getUploadTokens());
                }
            }
        } catch (Exception e) {
            log.error("评论图片处理失败: commentId={}, userId={}", comment.getId(), userId, e);
            // 图片处理失败不影响评论创建，只记录日志
        }
        
        // 记录用户活动
        userActivityService.recordActivity(userId, ActivityType.COMMENT_POSTED,
            "发表评论", comment.getId(), "comment", clientIp, userAgent, "SUCCESS", null);

        // 发送评论通知
        try {
            // 获取文章信息
            com.blog.cmrpersonalblog.entity.Article article = articleMapper.selectById(request.getArticleId());
            if (article != null) {
                if (request.isTopLevelComment()) {
                    // 顶级评论：通知文章作者
                    notificationService.sendCommentNotification(comment.getId(), userId, request.getArticleId(), article.getAuthorId());
                } else {
                    // 回复评论：通知被回复的用户
                    if (request.getReplyToUserId() != null) {
                        notificationService.sendReplyNotification(comment.getId(), userId, request.getReplyToUserId(), request.getArticleId());
                    }
                }
            }
        } catch (Exception e) {
            log.error("发送评论通知失败: commentId={}, userId={}", comment.getId(), userId, e);
            // 通知发送失败不影响评论创建
        }

        // 处理@提及功能
        try {
            // 从评论内容中提取@提及的用户ID
            List<Long> mentionedUserIds = MentionUtils.extractMentionedUserIds(comment.getContent());

            if (mentionedUserIds != null && !mentionedUserIds.isEmpty()) {
                log.info("检测到@提及: commentId={}, mentionedUserIds={}", comment.getId(), mentionedUserIds);

                // 验证被提及的用户是否存在
                List<Long> validUserIds = new ArrayList<>();
                for (Long mentionedUserId : mentionedUserIds) {
                    if (sysUserMapper.selectById(mentionedUserId) != null) {
                        validUserIds.add(mentionedUserId);
                    } else {
                        log.warn("被@提及的用户不存在: userId={}", mentionedUserId);
                    }
                }

                if (!validUserIds.isEmpty()) {
                    // 保存@提及记录
                    List<com.blog.cmrpersonalblog.entity.CommentMention> mentions = new ArrayList<>();
                    int position = 0;
                    for (Long mentionedUserId : validUserIds) {
                        com.blog.cmrpersonalblog.entity.CommentMention mention = new com.blog.cmrpersonalblog.entity.CommentMention();
                        mention.setCommentId(comment.getId());
                        mention.setArticleId(request.getArticleId());
                        mention.setMentionerId(userId);
                        mention.setMentionedUserId(mentionedUserId);
                        mention.setPosition(position++);
                        mention.setIsNotified(0); // 初始为未通知
                        mentions.add(mention);
                    }

                    // 批量插入@提及记录
                    if (!mentions.isEmpty()) {
                        commentMentionMapper.batchInsert(mentions);
                        log.info("@提及记录已保存: count={}", mentions.size());
                    }

                    // 发送@提及通知（排除已经收到评论/回复通知的用户）
                    List<Long> notifyUserIds = new ArrayList<>(validUserIds);

                    // 排除文章作者（如果是顶级评论，文章作者已收到评论通知）
                    com.blog.cmrpersonalblog.entity.Article article = articleMapper.selectById(request.getArticleId());
                    if (article != null && request.isTopLevelComment()) {
                        notifyUserIds.remove(article.getAuthorId());
                    }

                    // 排除被回复的用户（如果是回复评论，被回复用户已收到回复通知）
                    if (request.getReplyToUserId() != null) {
                        notifyUserIds.remove(request.getReplyToUserId());
                    }

                    // 发送@提及通知
                    if (!notifyUserIds.isEmpty()) {
                        notificationService.sendMentionNotification(
                            comment.getId(), userId, notifyUserIds, request.getArticleId()
                        );
                        log.info("@提及通知已发送: count={}", notifyUserIds.size());
                    }
                }
            }
        } catch (Exception e) {
            log.error("处理@提及失败: commentId={}, userId={}", comment.getId(), userId, e);
            // @提及处理失败不影响评论创建
        }

        // 返回创建的评论详情
        return getCommentDetail(comment.getId(), userId);
    }

    @Override
    @Transactional
    public CommentLikeResponse likeComment(CommentLikeRequest request, Long userId) {
        log.info("用户点赞评论: commentId={}, userId={}, liked={}", request.getCommentId(), userId, request.getLiked());
        
        Long commentId = request.getCommentId();
        
        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null || comment.getStatus() != 1) {
            throw new RuntimeException("评论不存在或已删除");
        }
        
        // 检查用户当前的点赞状态
        UserLike existingLike = userLikeMapper.selectUserLikeStatus(userId, commentId, UserLike.TARGET_TYPE_COMMENT);
        
        // 创建或更新点赞记录
        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setTargetId(commentId);
        userLike.setTargetType(UserLike.TARGET_TYPE_COMMENT);
        userLike.setStatus(request.getLiked() ? UserLike.STATUS_LIKE : UserLike.STATUS_UNLIKE);
        
        // 保存点赞状态
        userLikeMapper.insertOrUpdateUserLike(userLike);
        
        // 计算点赞数变化
        int likeCountChange = 0;
        if (existingLike == null) {
            // 之前没有记录，如果现在点赞则+1
            likeCountChange = request.getLiked() ? 1 : 0;
        } else {
            // 之前有记录，比较状态变化
            boolean wasLiked = existingLike.isLiked();
            boolean nowLiked = request.getLiked();
            
            if (wasLiked && !nowLiked) {
                likeCountChange = -1; // 从点赞变为取消点赞
            } else if (!wasLiked && nowLiked) {
                likeCountChange = 1; // 从取消点赞变为点赞
            }
            // 如果状态没有变化（wasLiked == nowLiked），则likeCountChange = 0
        }
        
        log.debug("点赞状态变化: existingLike={}, requestLiked={}, likeCountChange={}", 
                 existingLike != null ? existingLike.isLiked() : "null", request.getLiked(), likeCountChange);
        
        // 更新评论的点赞数
        if (likeCountChange != 0) {
            commentManagementService.updateCommentStats(commentId, "like_count", likeCountChange);
        }
        
        // 获取最新的点赞数
        Comment updatedComment = commentMapper.selectById(commentId);
        
        // 记录用户活动
        String activityDesc = request.getLiked() ? "点赞评论" : "取消点赞评论";
        userActivityService.recordActivity(userId, ActivityType.ARTICLE_LIKED,
            activityDesc, commentId, "comment", null, null, "SUCCESS", null);

        // 发送点赞通知（仅在点赞时发送，取消点赞不发送）
        if (request.getLiked() && likeCountChange > 0) {
            try {
                notificationService.sendLikeNotification(userId, commentId, "comment", comment.getUserId());
            } catch (Exception e) {
                log.error("发送评论点赞通知失败: commentId={}, userId={}", commentId, userId, e);
                // 通知发送失败不影响点赞操作
            }
        }

        log.info("评论点赞操作完成: commentId={}, newLikeCount={}", commentId, updatedComment.getLikeCount());

        return request.getLiked()
            ? CommentLikeResponse.liked(commentId, updatedComment.getLikeCount())
            : CommentLikeResponse.unliked(commentId, updatedComment.getLikeCount());
    }

    @Override
    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    public ArticleCommentResponse getCommentDetail(Long commentId, Long userId) {
        log.info("获取评论详情: commentId={}, userId={}", commentId, userId);
        
        // 如果未传入用户ID，尝试获取当前登录用户ID
        if (userId == null) {
            try {
                if (StpUtil.isLogin()) {
                    userId = StpUtil.getLoginIdAsLong();
                }
            } catch (Exception e) {
                // 用户未登录，忽略异常
            }
        }
        
        ArticleCommentResponse response = commentMapper.selectCommentDetailForUser(commentId, userId);
        if (response == null) {
            throw new RuntimeException("评论不存在或已删除");
        }
        
        return response;
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId) {
        log.info("用户删除评论: commentId={}, userId={}", commentId, userId);
        
        // 检查评论是否存在
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 检查是否是评论作者
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("只能删除自己的评论");
        }
        
        // 检查评论是否已删除
        if (comment.getStatus() == 0) {
            throw new RuntimeException("评论已删除");
        }
        
        // 获取即将被删除的评论ID列表（包括所有子评论）
        List<Long> commentIdsToDelete = commentMapper.selectCommentAndRepliesIds(commentId);
        
        // 在删除评论前，先将相关图片状态设置为已删除
        if (commentIdsToDelete != null && !commentIdsToDelete.isEmpty()) {
            try {
                commentImageService.updateCommentsImagesStatus(commentIdsToDelete, 0);
                log.info("评论图片状态已更新为已删除: commentIds={}", commentIdsToDelete);
            } catch (Exception e) {
                log.error("更新评论图片状态失败: commentIds={}", commentIdsToDelete, e);
                // 继续执行评论删除，即使图片状态更新失败
            }
        }
        
        // 用户端硬删除评论（包括所有子评论）
        int deleted = commentMapper.hardDeleteCommentAndReplies(commentId);
        
        if (deleted > 0) {
            // 重新计算文章评论数量（基于实际评论数）
            try {
                articleMapper.recalculateArticleCommentCount(comment.getArticleId());
                log.debug("文章评论数量已重新计算: articleId={}", comment.getArticleId());
            } catch (Exception e) {
                log.error("重新计算文章评论数量失败: articleId={}", comment.getArticleId(), e);
            }
            
            // 如果是回复评论，更新父评论的回复数
            if (comment.getParentId() != null && comment.getParentId() > 0) {
                try {
                    commentManagementService.updateCommentStats(comment.getParentId(), "reply_count", -1);
                } catch (Exception e) {
                    log.error("更新父评论回复数失败: parentId={}", comment.getParentId(), e);
                }
            }
            
            // 记录用户活动
            userActivityService.recordActivity(userId, ActivityType.COMMENT_POSTED, 
                "删除评论", commentId, "comment", null, null, "SUCCESS", null);
            
            log.info("评论删除成功: commentId={}, 删除评论数: {}", commentId, deleted);
        }
        
        return deleted > 0;
    }

    @Override
    public boolean canUserComment(Long articleId, Long userId) {
        // 检查文章是否存在且可评论
        return commentMapper.checkArticleCommentable(articleId);
    }

    @Override
    public CommentStatsResponse getCommentStats(Long commentId) {
        log.info("获取评论统计: commentId={}", commentId);
        
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 获取当前用户的点赞状态
        Boolean isLiked = false;
        try {
            if (StpUtil.isLogin()) {
                Long userId = StpUtil.getLoginIdAsLong();
                UserLike userLike = userLikeMapper.selectUserLikeStatus(userId, commentId, UserLike.TARGET_TYPE_COMMENT);
                isLiked = userLike != null && userLike.isLiked();
            }
        } catch (Exception e) {
            // 用户未登录，忽略异常
        }
        
        return new CommentStatsResponse(commentId, comment.getLikeCount(), comment.getReplyCount(), isLiked);
    }

    /**
     * 计算评论及其所有子评论的数量
     */
    private int countCommentAndReplies(Long commentId) {
        try {
            return commentMapper.countCommentAndReplies(commentId);
        } catch (Exception e) {
            log.error("计算评论及子评论数量失败: commentId={}", commentId, e);
            return 1; // 至少删除当前评论
        }
    }
}
